package com.beauty.logistics.service.impl;

import com.beauty.logistics.dto.CarrierRequest;
import com.beauty.logistics.dto.CarrierResponse;
import com.beauty.logistics.entity.Carrier;
import com.beauty.logistics.exception.LogisticsException;
import com.beauty.logistics.repository.CarrierRepository;
import com.beauty.logistics.service.CarrierService;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CarrierServiceImpl implements CarrierService {
    
    private final CarrierRepository carrierRepository;
    
    @Override
    @Transactional
    public CarrierResponse createCarrier(CarrierRequest carrierRequest) {
        // 检查承运商名称是否已存在
        if (carrierRepository.findByName(carrierRequest.getName()).isPresent()) {
            throw new LogisticsException("承运商名称已存在: " + carrierRequest.getName());
        }
        
        // 检查承运商代码是否已存在
        if (carrierRequest.getCode() != null && carrierRepository.findByCode(carrierRequest.getCode()).isPresent()) {
            throw new LogisticsException("承运商代码已存在: " + carrierRequest.getCode());
        }
        
        Carrier carrier = new Carrier();
        carrier.setName(carrierRequest.getName());
        carrier.setCode(carrierRequest.getCode());
        carrier.setContactPerson(carrierRequest.getContactPerson());
        carrier.setContactEmail(carrierRequest.getContactEmail());
        carrier.setContactPhone(carrierRequest.getContactPhone());
        carrier.setTrackingUrlTemplate(carrierRequest.getTrackingUrlTemplate());
        carrier.setApiCredentials(carrierRequest.getApiCredentials());
        carrier.setIsActive(carrierRequest.getIsActive() != null ? carrierRequest.getIsActive() : true);
        carrier.setSupportedCountries(carrierRequest.getSupportedCountries());
        carrier.setServiceOptions(carrierRequest.getServiceOptions());
        
        Carrier savedCarrier = carrierRepository.save(carrier);
        return CarrierResponse.fromEntity(savedCarrier);
    }
    
    @Override
    public CarrierResponse getCarrierById(Long id) {
        Carrier carrier = carrierRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("承运商不存在，ID: " + id));
        return CarrierResponse.fromEntity(carrier);
    }
    
    @Override
    public CarrierResponse getCarrierByName(String name) {
        Carrier carrier = carrierRepository.findByName(name)
                .orElseThrow(() -> new EntityNotFoundException("承运商不存在，名称: " + name));
        return CarrierResponse.fromEntity(carrier);
    }
    
    @Override
    public CarrierResponse getCarrierByCode(String code) {
        Carrier carrier = carrierRepository.findByCode(code)
                .orElseThrow(() -> new EntityNotFoundException("承运商不存在，代码: " + code));
        return CarrierResponse.fromEntity(carrier);
    }
    
    @Override
    public List<CarrierResponse> getActiveCarriers() {
        return carrierRepository.findByIsActive(true)
                .stream()
                .map(CarrierResponse::fromEntity)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<CarrierResponse> getCarriersByCountry(String country) {
        return carrierRepository.findBySupportedCountriesContaining(country)
                .stream()
                .map(CarrierResponse::fromEntity)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<CarrierResponse> getAllCarriers() {
        return carrierRepository.findAll()
                .stream()
                .map(CarrierResponse::fromEntity)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public CarrierResponse updateCarrier(Long id, CarrierRequest carrierRequest) {
        Carrier carrier = carrierRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("承运商不存在，ID: " + id));
        
        // 检查名称唯一性
        if (!carrier.getName().equals(carrierRequest.getName())) {
            carrierRepository.findByName(carrierRequest.getName())
                    .ifPresent(existingCarrier -> {
                        if (!existingCarrier.getId().equals(id)) {
                            throw new LogisticsException("承运商名称已存在: " + carrierRequest.getName());
                        }
                    });
        }
        
        // 检查代码唯一性
        if (carrierRequest.getCode() != null && !carrierRequest.getCode().equals(carrier.getCode())) {
            carrierRepository.findByCode(carrierRequest.getCode())
                    .ifPresent(existingCarrier -> {
                        if (!existingCarrier.getId().equals(id)) {
                            throw new LogisticsException("承运商代码已存在: " + carrierRequest.getCode());
                        }
                    });
        }
        
        carrier.setName(carrierRequest.getName());
        carrier.setCode(carrierRequest.getCode());
        carrier.setContactPerson(carrierRequest.getContactPerson());
        carrier.setContactEmail(carrierRequest.getContactEmail());
        carrier.setContactPhone(carrierRequest.getContactPhone());
        carrier.setTrackingUrlTemplate(carrierRequest.getTrackingUrlTemplate());
        carrier.setApiCredentials(carrierRequest.getApiCredentials());
        
        if (carrierRequest.getIsActive() != null) {
            carrier.setIsActive(carrierRequest.getIsActive());
        }
        
        carrier.setSupportedCountries(carrierRequest.getSupportedCountries());
        carrier.setServiceOptions(carrierRequest.getServiceOptions());
        
        Carrier updatedCarrier = carrierRepository.save(carrier);
        return CarrierResponse.fromEntity(updatedCarrier);
    }
    
    @Override
    @Transactional
    public CarrierResponse toggleCarrierStatus(Long id, Boolean isActive) {
        Carrier carrier = carrierRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("承运商不存在，ID: " + id));
        
        carrier.setIsActive(isActive);
        
        Carrier updatedCarrier = carrierRepository.save(carrier);
        return CarrierResponse.fromEntity(updatedCarrier);
    }
    
    @Override
    @Transactional
    public void deleteCarrier(Long id) {
        if (!carrierRepository.existsById(id)) {
            throw new EntityNotFoundException("承运商不存在，ID: " + id);
        }
        carrierRepository.deleteById(id);
    }
} 